package ycl.security.exception;

import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.AuthenticationException;
import org.springframework.stereotype.Component;
import ycl.common.result.Result;
import ycl.common.exception.CustomException;
import ycl.common.utils.ServletUtil;

import javax.servlet.*;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * security异常处理
 *
 * @author ycl
 * @date 2022/10/6 0006 13:34:13
 */
@Component
@Slf4j
public class ExceptionInterceptor implements Filter {
	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException {
		log.info("Filter . doFilter . 异常处理");
		try {
			chain.doFilter(request, response);
		} catch (Exception e) {
			writeResponse(response, e);
		}
	}


	private void writeResponse(ServletResponse resp, Exception e) throws IOException {
		HttpServletResponse response = (HttpServletResponse) resp;
		Result<Object> result;
		if (e instanceof CustomException) {
			CustomException exception = (CustomException) e;
			result = Result.fail(exception.getEnums());
		} else if (e instanceof AuthenticationException) {
			result = Result.fail(e.getMessage());
		} else {
			log.error("{}", e.getMessage(), e);
			result = Result.fail();
		}
		ServletUtil.writeResponse(response, result);
	}
}
